<?php

namespace App\Admin\Forms;

use App\Models\Setting;
use Dcat\Admin\Widgets\Form;
use Symfony\Component\HttpFoundation\Response;

class SettingForm extends Form
{
    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return mixed
     */
    public function handle(array $input)
    {
        //进行保存操作
        $setting = new Setting();
        $where = [];
        $where['sms_open'] = $input['sms_open'] ?? 0;
        $where['carousel_map'] = $input['carousel_map'] ?? [];
        $where['web_name'] = $input['web_name'] ?? '';
        $where['img_pre'] = $input['img_pre'] ?? '';
        $result = $setting->whereIn('key',$where)->update([
            'sms_open'=>$sms_open,
            'carousel_map'=>$carousel_map,
            'web_name'=>$web_name,
            'img_pre'=>$img_pre,
            ]);
        if ($result) {
            return $this->success('配置更新成功！');
        } else {
            return $this
                ->error('保存失败');
        }

    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $default = Setting::all()->pluck('value', 'key')->toArray();

        $carousel_map = json_decode($default['carousel_map']);
        $a = [];
        foreach ($carousel_map as $v) {
            $a[] = $default['img_pre'] . '/' . $v;
        }
        $a = $a ?? '';
        //查找默认值
        $this->switch('sms_open', '短信开关')
            ->default($default['sms_open']);
        $this->text('kefu_phone', '客服电话')->default($default['kefu_phone']);
        $this->text('web_name', '站点名称')->default($default['img_pre']);
        $this->multipleImage('carousel_map', '轮播图')->accept('jpg,png,gif,jpeg')->uniqueName()->autoUpload()->default($a);
    }
}
